package com.yingying.tools;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @ClassName: AmberBakery
 * @Description:
 * @author chendong
 * @date 2017年3月26日 上午10:00:57 */
public class Tools {	
	public static Date getsimpleDatefromString(String date) {
		SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sp.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
		
	/**
	 *	input流转字节数组 
	 * @param input
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray(InputStream input) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    byte[] buffer = new byte[4096];
	    int n = 0;
	    while (-1 != (n = input.read(buffer))) {
	        output.write(buffer, 0, n);
	    }
	    return output.toByteArray();
	}
	
	   /**
     * POST方式发起http请求
     */
    public static String requestByPostMethod(String url, Map<String,String> params,Map<String,String> headerMap){
    	String result = null;
        CloseableHttpClient httpClient = getHttpClient();
        try {
            HttpPost postMethod = new HttpPost(url);          //这里用上本机的某个工程做测试
//            httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
            //创建参数列表
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if(params!=null)
            {
            	for(Entry<String,String> param : params.entrySet())
                {
                	list.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
            }
           
            //创建请求头信息列表
            for(Entry<String, String> header : headerMap.entrySet())
            {
            	postMethod.setHeader(header.getKey(), header.getValue());
            }
            
            //url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,"UTF-8");
            postMethod.setEntity(uefEntity);
            //执行请求
            CloseableHttpResponse httpResponse = httpClient.execute(postMethod);
            try{
	            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
	            {
	            	HttpEntity entity = httpResponse.getEntity();
					if (null != entity) {
						InputStream in = entity.getContent();
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(in, "UTF-8"));
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line);
						}
						result = sb.toString();
						reader.close();
						in.close();
						postMethod.releaseConnection();
						// //清楚浏览器缓存
						httpResponse.setHeader("Cache-Control", "no-store");
						httpResponse.setHeader("Pragrma", "no-cache");
						httpResponse.close();
						EntityUtils.consume(entity);
					}
	            }
            } finally{
                httpResponse.close();
            } 
             
        } catch( UnsupportedEncodingException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try{
                closeHttpClient(httpClient);                
            } catch(Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }
     
    private static CloseableHttpClient getHttpClient(){
        return HttpClients.createDefault();
    }
    
    private static void closeHttpClient(CloseableHttpClient client) throws IOException{
        if (client != null){
            client.close();
        }
    }
    
    
	
}
